package com.zh.dynamicproxyforandroid;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.zh.dynamicproxyforandroid.proxy.ProxyFactoryByCglib;
import com.zh.dynamicproxyforandroid.proxy.ProxyFactoryByJdk;
import com.zh.dynamicproxyforandroid.service.UserService;
import com.zh.dynamicproxyforandroid.service.impl.UserServiceImpl;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button jdkProxyBtn = findViewById(R.id.jdk_proxy_btn);
        Button cgLibProxyBtn = findViewById(R.id.cg_lib_proxy_btn);
        jdkProxyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testJdkProxy();
            }
        });
        cgLibProxyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testCglibProxy();
            }
        });
    }

    /**
     * jdk动态代理测试
     */
    private void testJdkProxy() {
        //创建目标对象
        UserServiceImpl userService = new UserServiceImpl();

        //对目标对象增强返回代理对象
        UserService proxy = (UserService) ProxyFactoryByJdk.getProxy(userService);
        System.out.println(proxy.getClass());

        //调用代理对象的方法
        proxy.save();
    }

    /**
     * cglib动态代理测试
     */
    private void testCglibProxy() {
        //创建目标对象
        UserServiceImpl userService = new UserServiceImpl();

        //对目标对象增强返回代理对象
        UserServiceImpl proxy = (UserServiceImpl) ProxyFactoryByCglib.getProxy(getApplicationContext(), userService);
        System.out.println(proxy.getClass());

        //调用代理对象的方法
        proxy.save();
    }
}